package net.lainiao.morethread.Chapter5.demo4;

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/3/6.
 */
public class Task extends RecursiveTask<Integer> {
    private int array[];
    private int start, end;

    public Task(int array[], int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        System.out.println("Task Start from "+start +" to "+end);
        if(end-start<10){
            if(start<3&&end>3){
                throw new RuntimeException("this task throws an Exception : Task from "+start+" to "+end);
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            int mid=(end+start)/2;
            Task task1=new Task(array,start,mid);
            Task task2=new Task(array,mid,end);
            invokeAll(task1,task2);
        }
        System.out.println("Task end from "+start+" to "+end);
        return 0;
    }
}
